﻿using ControleRepresentante.Logic.Models;
using NHibernate;
using NHibernate.Criterion;

namespace ControleRepresentante.Logic.Repositories.SearchExtensions
{
    public class RelatorioVisitaSearchExtension : ISearchExtension
    {
        private readonly RelatorioVisitaJolitexOcorrencia? m_Ocorrencia;

        public RelatorioVisitaSearchExtension(RelatorioVisitaJolitexOcorrencia? ocorrencia)
        {
            m_Ocorrencia = ocorrencia;
        }

        public ICriteria Execute(ICriteria criteria, string tableAlias)
        {
            if (m_Ocorrencia.HasValue)
            {
                DetachedCriteria detachedCriteria = DetachedCriteria.For<RelatorioVisitaJolitex>()
                    .SetProjection(Projections.Property<RelatorioVisitaJolitex>(x => x.Id))
                    .Add(Restrictions.EqProperty(tableAlias + ".Id", Projections.Property<RelatorioVisitaJolitex>(x => x.Id)))
                    .Add(Restrictions.Eq(Projections.Property<RelatorioVisitaJolitex>(x => x.Ocorrencia), m_Ocorrencia.Value));

                criteria = criteria.Add(Subqueries.Exists(detachedCriteria));
            }
            return criteria;
        }
    }
}
